package com.distributedDataBase.controller;

import com.distributedDataBase.pojo.Result;
import com.distributedDataBase.pojo.User;
import com.distributedDataBase.service.UserService;
import com.distributedDataBase.util.EmailUtil;
import com.distributedDataBase.util.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private EmailUtil emailUtil;

    @GetMapping("{email}")
    public Result sendCode(@PathVariable("email") String email, HttpServletRequest request) {
        // 1、判断email在db中是否存在
        User user = userService.searchUserByEmail(email);

        // 2、邮箱不存在，返回500
        if (user == null) {
            return new Result("404", "找不到你的码", email);
        }

        // 3、邮箱存在 -> 发送验证码

        // 随机生成6为的验证码[100000, 999999]
        int codeInt = (int) (Math.random()*90000+100000);
        String code = String.valueOf(codeInt);

        //获取HttpSession对象
        HttpSession session = request.getSession();
        //保存的数据的格式是key-value的形式
        session.setAttribute("serverCode", code);

        emailUtil.send(email, code);
        return new Result("200", "发送邮箱成功", email);

    }

    //登录
    @PostMapping("{email}/{code}")
    public Result login(@PathVariable("email")String email, @PathVariable("code")String code, HttpServletRequest request){
        //1. 判断email在db表中是否是存在的
        User user = userService.searchUserByEmail(email);
        if(null == user)
            return new Result("404","email is not exists!");


        //比较验证码
        //从session中根据key获取
        HttpSession session = request.getSession();
        String serverCode = (String) session.getAttribute("serverCode");
        //TODO... 数据的校验
        if(!code.equals(serverCode)){
            return new Result("500","code is not right!");
        }

        //生成token
        String token = JWTUtils.geneJsonWebToken(user);

        return new Result("200","login success",token);
    }

}
